<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * 能力维度模型
 * 定义员工能力评定的各个维度
 */
class AbilityDimension extends Model
{
    use HasFactory;

    /**
     * 表名
     */
    protected $table = 'ability_dimensions';

    /**
     * 可填充字段
     */
    protected $fillable = [
        'name',
        'code',
        'description',
        'category',
        'weight',
        'max_score',
        'min_score',
        'score_type',
        'score_levels',
        'applicable_positions',
        'evaluation_criteria',
        'evaluation_examples',
        'is_active',
        'sort_order',
        'is_required',
        'usage_count',
        'average_score',
    ];

    /**
     * 字段类型转换
     */
    protected $casts = [
        'weight' => 'integer',
        'max_score' => 'integer',
        'min_score' => 'integer',
        'is_active' => 'boolean',
        'is_required' => 'boolean',
        'usage_count' => 'integer',
        'average_score' => 'decimal:2',
        'score_levels' => 'array',
        'applicable_positions' => 'array',
        'evaluation_examples' => 'array',
    ];

    /**
     * 日期字段
     */
    protected $dates = [
        'created_at',
        'updated_at',
    ];

    // ============ 常量定义 ============

    public const CATEGORY_PROFESSIONAL = 'professional';
    public const CATEGORY_LEADERSHIP = 'leadership';
    public const CATEGORY_COMMUNICATION = 'communication';
    public const CATEGORY_EXECUTION = 'execution';
    public const CATEGORY_INNOVATION = 'innovation';

    public const SCORE_TYPE_NUMERIC = 'numeric';
    public const SCORE_TYPE_GRADE = 'grade';
    public const SCORE_TYPE_LEVEL = 'level';

    // ============ 关联关系 ============

    /**
     * 关联能力评定记录
     */
    public function assessments(): HasMany
    {
        return $this->hasMany(AbilityAssessment::class);
    }

    // ============ 访问器 ============

    /**
     * 获取分类标签
     */
    public function getCategoryLabelAttribute(): string
    {
        return match($this->category) {
            self::CATEGORY_PROFESSIONAL => '专业能力',
            self::CATEGORY_LEADERSHIP => '领导能力',
            self::CATEGORY_COMMUNICATION => '沟通能力',
            self::CATEGORY_EXECUTION => '执行能力',
            self::CATEGORY_INNOVATION => '创新能力',
            default => $this->category ?? '未知'
        };
    }

    /**
     * 获取评分类型标签
     */
    public function getScoreTypeLabelAttribute(): string
    {
        return match($this->score_type) {
            self::SCORE_TYPE_NUMERIC => '数值评分',
            self::SCORE_TYPE_GRADE => '等级评分',
            self::SCORE_TYPE_LEVEL => '水平评分',
            default => $this->score_type ?? '未知'
        };
    }

    /**
     * 获取评分范围
     */
    public function getScoreRangeAttribute(): string
    {
        return "{$this->min_score} - {$this->max_score}";
    }

    /**
     * 获取是否启用标签
     */
    public function getActiveStatusAttribute(): string
    {
        return $this->is_active ? '启用' : '禁用';
    }

    /**
     * 获取是否必评标签
     */
    public function getRequiredStatusAttribute(): string
    {
        return $this->is_required ? '必评' : '选评';
    }

    /**
     * 获取平均分百分比
     */
    public function getAverageScorePercentageAttribute(): ?float
    {
        if (!$this->average_score || !$this->max_score) {
            return null;
        }

        return round(($this->average_score / $this->max_score) * 100, 1);
    }

    // ============ 作用域 ============

    /**
     * 启用状态作用域
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 必评项目作用域
     */
    public function scopeRequired($query)
    {
        return $query->where('is_required', true);
    }

    /**
     * 按分类筛选作用域
     */
    public function scopeByCategory($query, $category)
    {
        return $query->where('category', $category);
    }

    /**
     * 按评分类型筛选作用域
     */
    public function scopeByScoreType($query, $scoreType)
    {
        return $query->where('score_type', $scoreType);
    }

    /**
     * 按权重排序作用域
     */
    public function scopeOrderByWeight($query)
    {
        return $query->orderBy('weight', 'desc');
    }

    /**
     * 按排序字段排序作用域
     */
    public function scopeOrderBySort($query)
    {
        return $query->orderBy('sort_order')->orderBy('name');
    }

    // ============ 业务方法 ============

    /**
     * 启用维度
     */
    public function activate(): bool
    {
        $this->is_active = true;
        return $this->save();
    }

    /**
     * 禁用维度
     */
    public function deactivate(): bool
    {
        $this->is_active = false;
        return $this->save();
    }

    /**
     * 设置为必评
     */
    public function setRequired(): bool
    {
        $this->is_required = true;
        return $this->save();
    }

    /**
     * 设置为选评
     */
    public function setOptional(): bool
    {
        $this->is_required = false;
        return $this->save();
    }

    /**
     * 更新评分等级
     */
    public function updateScoreLevels(array $scoreLevels): bool
    {
        $this->score_levels = $scoreLevels;
        return $this->save();
    }

    /**
     * 添加适用岗位
     */
    public function addApplicablePosition(string $position): bool
    {
        $positions = $this->applicable_positions ?? [];
        if (!in_array($position, $positions)) {
            $positions[] = $position;
            $this->applicable_positions = $positions;
            return $this->save();
        }
        return true;
    }

    /**
     * 移除适用岗位
     */
    public function removeApplicablePosition(string $position): bool
    {
        $positions = $this->applicable_positions ?? [];
        $positions = array_diff($positions, [$position]);
        $this->applicable_positions = array_values($positions);
        return $this->save();
    }

    /**
     * 检查岗位是否适用
     */
    public function isApplicableToPosition(string $position): bool
    {
        if (empty($this->applicable_positions)) {
            return true; // 如果没有设置适用岗位，则适用于所有岗位
        }

        return in_array($position, $this->applicable_positions);
    }

    /**
     * 更新使用统计
     */
    public function updateUsageStats(): bool
    {
        $assessmentCount = $this->assessments()->count();
        $averageScore = $this->assessments()->avg('score'); // 这里需要调整，根据实际评分字段

        $this->usage_count = $assessmentCount;
        $this->average_score = $averageScore;

        return $this->save();
    }

    // ============ 静态方法 ============

    /**
     * 获取分类选项
     */
    public static function getCategoryOptions(): array
    {
        return [
            self::CATEGORY_PROFESSIONAL => '专业能力',
            self::CATEGORY_LEADERSHIP => '领导能力',
            self::CATEGORY_COMMUNICATION => '沟通能力',
            self::CATEGORY_EXECUTION => '执行能力',
            self::CATEGORY_INNOVATION => '创新能力',
        ];
    }

    /**
     * 获取评分类型选项
     */
    public static function getScoreTypeOptions(): array
    {
        return [
            self::SCORE_TYPE_NUMERIC => '数值评分',
            self::SCORE_TYPE_GRADE => '等级评分',
            self::SCORE_TYPE_LEVEL => '水平评分',
        ];
    }

    /**
     * 创建默认能力维度
     */
    public static function createDefaultDimensions(): array
    {
        $dimensions = [
            [
                'name' => '专业技能',
                'code' => 'professional_skill',
                'description' => '专业技术能力和业务技能水平',
                'category' => self::CATEGORY_PROFESSIONAL,
                'weight' => 25,
                'max_score' => 100,
                'min_score' => 0,
                'score_type' => self::SCORE_TYPE_NUMERIC,
                'is_required' => true,
                'sort_order' => 1,
            ],
            [
                'name' => '工作态度',
                'code' => 'work_attitude',
                'description' => '工作责任心、积极性、团队协作精神',
                'category' => self::CATEGORY_EXECUTION,
                'weight' => 20,
                'max_score' => 100,
                'min_score' => 0,
                'score_type' => self::SCORE_TYPE_NUMERIC,
                'is_required' => true,
                'sort_order' => 2,
            ],
            [
                'name' => '沟通能力',
                'code' => 'communication',
                'description' => '口头表达、书面沟通、人际交往能力',
                'category' => self::CATEGORY_COMMUNICATION,
                'weight' => 15,
                'max_score' => 100,
                'min_score' => 0,
                'score_type' => self::SCORE_TYPE_NUMERIC,
                'is_required' => true,
                'sort_order' => 3,
            ],
            [
                'name' => '执行力',
                'code' => 'execution',
                'description' => '任务执行效率、质量控制、时间管理',
                'category' => self::CATEGORY_EXECUTION,
                'weight' => 20,
                'max_score' => 100,
                'min_score' => 0,
                'score_type' => self::SCORE_TYPE_NUMERIC,
                'is_required' => true,
                'sort_order' => 4,
            ],
            [
                'name' => '领导能力',
                'code' => 'leadership',
                'description' => '团队管理、决策能力、指导他人能力',
                'category' => self::CATEGORY_LEADERSHIP,
                'weight' => 20,
                'max_score' => 100,
                'min_score' => 0,
                'score_type' => self::SCORE_TYPE_NUMERIC,
                'is_required' => false,
                'sort_order' => 5,
            ],
        ];

        $createdDimensions = [];
        foreach ($dimensions as $dimensionData) {
            $dimension = self::create($dimensionData);
            $createdDimensions[] = $dimension;
        }

        return $createdDimensions;
    }

    /**
     * 验证维度数据
     */
    public static function validateDimensionData(array $data): array
    {
        $errors = [];

        // 必填字段验证
        $requiredFields = ['name', 'code', 'category'];
        foreach ($requiredFields as $field) {
            if (empty($data[$field])) {
                $errors[] = "{$field} 字段不能为空";
            }
        }

        // 编码唯一性验证
        if (!empty($data['code'])) {
            $query = self::where('code', $data['code']);
            if (isset($data['id'])) {
                $query->where('id', '!=', $data['id']);
            }
            if ($query->exists()) {
                $errors[] = "编码 {$data['code']} 已存在";
            }
        }

        // 分类验证
        $validCategories = array_keys(self::getCategoryOptions());
        if (!empty($data['category']) && !in_array($data['category'], $validCategories)) {
            $errors[] = "无效的分类";
        }

        // 评分类型验证
        $validScoreTypes = array_keys(self::getScoreTypeOptions());
        if (!empty($data['score_type']) && !in_array($data['score_type'], $validScoreTypes)) {
            $errors[] = "无效的评分类型";
        }

        // 数值范围验证
        if (!empty($data['weight']) && (!is_numeric($data['weight']) || $data['weight'] < 0 || $data['weight'] > 100)) {
            $errors[] = "权重必须在0-100之间";
        }

        if (!empty($data['max_score']) && !empty($data['min_score']) && $data['min_score'] >= $data['max_score']) {
            $errors[] = "最低分必须小于最高分";
        }

        return $errors;
    }
}
